<?php

declare(strict_types=1);

namespace app\common\event;

use app\common\utils\SwooleUtil;
use think\App;
use think\facade\Log;
use think\swoole\Manager;

class CreateProcess
{
    protected $manager;
    public function __construct(App $app)
    {
        $this->manager         = $app->make(Manager::class);
    }
    public function handle()
    {
        $this->manager->addWorker(function () {
            $this->manager->runWithBarrier(function () {
                $this->process();
            });
        }, 'xhadmin-process');
    }
    public function process()
    {
        try {
            $process = SwooleUtil::getProcess();
            if (empty($process)) {
                return;
            }
            foreach ($process as $key => $value) {
                try {
                    $class = new $value['class'];
                    $class->{$value['handler']}();
                } catch (\Throwable $th) {
                    Log::channel('swoole')->error("{$key} process error：{$th->getMessage()}，file：{$th->getFile()}:{$th->getLine()}");
                }
            }
            Log::channel('swoole')->info('create process start：' . date('Y-m-d H:i:s'));
        } catch (\Throwable $th) {
            Log::channel('swoole')->error("create process error：{$th->getMessage()}，file：{$th->getFile()}:{$th->getLine()}");
        }
    }
}
